package springboot.producer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xq.softcup.mq.client.message.MqMessage;
import org.xq.softcup.mq.client.producer.MqProducer;

@Slf4j
@Controller
public class TestProducer {

	@RequestMapping("/")
	public String index(){
		return "index";
	}

    int n = 0;
	@RequestMapping("/produce")
	@ResponseBody
	public String produce(int type){

		String topic_order = "topic_order";
		String topic_1 = "topic_1";
		String data = "数据:"+(++n)+" 时间戳:"  + System.currentTimeMillis();
		if (type == 1) {//单个消息发送
			MqProducer.produce(new MqMessage(topic_1, data));
		} else if (type == 2) {//广播消费
			MqProducer.broadcast(new MqMessage(topic_1, data));
		} else if (type == 3) {//批量发送消息
			long start = System.currentTimeMillis();
			for (int i = 1; i <= Contants.COUNT; i++) {
				String str = String.format("Msg:%d", i);
				MqProducer.produce(new MqMessage(topic_order, str));
			}
			long end = System.currentTimeMillis();
			String msg = String.format("topic_order生产者发送{%d}条消息，耗时: %s ms", Contants.COUNT , (end-start));
			log.info(msg);
		}
		return "SUCCESS";
	}

	@ExceptionHandler({Exception.class})
     public String exception(Exception e) {
         e.printStackTrace();
         return e.getMessage();
     }

}
